package io.jee.caisan.weixin.handler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import io.jee.alaska.httpclient.HttpClientHelper;
import io.jee.alaska.httpclient.HttpResult;
import io.jee.caisan.weixin.builder.TextBuilder;
import io.jee.caisan.weixin.config.UrlManager;
import io.jee.caisan.weixin.domain.SysActivity;
import io.jee.caisan.weixin.service.ActivityService;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
public class MsgHandler extends AbstractHandler {
	
	@Resource
	private HttpClientHelper httpClientHelper;
	
	@Resource
	private ActivityService activityService;
	
	@Resource
	private UrlManager urlManager;

	@Override
	public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService weixinService, WxSessionManager sessionManager) {
		
		String content = wxMessage.getContent();
		
		if(StringUtils.isNotBlank(content)) {
			
			//固定关键字回复必需放在图灵机器人之前
			if(content.startsWith("彩伞宝宝:") || content.startsWith("彩伞宝宝：")) {
				content = content.substring(5, content.length());
				WxMpXmlOutMessage out = activityService.auto(wxMessage, SysActivity.TYPE_1, content);
				if(out == null) {
					return new TextBuilder().build("暂无活动", wxMessage, weixinService);
				} 
				return out;
			}
			
			//调用图灵机器人
			Map<String, Object> postData = new HashMap<>();
			postData.put("key", "1408933270a04265b5b19f316f140847");
			postData.put("info", content);
			postData.put("userid", wxMessage.getFromUser());
			
			ObjectMapper objectMapper = new ObjectMapper();
			
			try {
				HttpResult httpResult = httpClientHelper.post("http://www.tuling123.com/openapi/api", objectMapper.writeValueAsString(postData));
				if(httpResult.isSuccess()) {
					JsonNode rootNode = objectMapper.readTree(httpResult.getContent());
					int code = rootNode.get("code").intValue();
					if(code == 100000) {
						return new TextBuilder().build(rootNode.get("text").asText(), wxMessage, weixinService);
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		
		return null;

	}
	
}
